package com.opc.Controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.opc.Common.Code;
import com.opc.Common.MessageConstant;
import com.opc.Common.Result;
import com.opc.Mapper.EmployeeMapper;
import com.opc.Pojo.Admin;
import com.opc.Pojo.Employee;
import com.opc.Service.AdminService;
import com.opc.properties.IpProperties;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

@Slf4j
@RestController
@RequestMapping("/Admin")
public class AdminController {

    @Autowired
    private AdminService adminService; // 注入 OpcUaService
    @Autowired
    private EmployeeMapper employeeMapper;

//    @Autowired
//    private IpProperties ipProperties;
    @Value("${jwt.path}")
    private String SECRET_KEY;
    //密钥，用于签名JWT
//    private static final String SECRET_KEY = ipProperties.get;
    // token过期时间，这里设置为1小时
//    private static final long EXPIRATION_TIME = MessageConstant.tokenExpirationTime; // 1 hour in milliseconds

    Date now = new Date();
//    Date expiryDate = new Date(now.getTime() + (2 * 24 * 60 * 60 * 1000)); // 2天后过期

//    Date expiryDate0 = new Date(now.getTime() + (10 * 1000)); // 10秒后过期

//    Date expiryDate = new Date(now.getTime() + (2 * 24 * 60 * 60 * 1000)); // 2天后过期

    private static final long EXPIRY_INTERVAL = 2 * 24 * 60 * 60 * 1000;

    // 定义一个表示“10秒”的时间间隔常量（单位：毫秒）
//    private static final long EXPIRY_INTERVAL = 10 * 1000; // 10秒 = 10,000毫秒

    @PostMapping("/login")
    @CrossOrigin
    public Result login(@RequestBody Admin admin) {
        LambdaQueryWrapper<Admin> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Admin::getUsername, admin.getUsername().trim());
        Admin adminQuery = adminService.getOne(queryWrapper);

        if (adminQuery == null) {
            return new Result(Code.LOGIN_ERR, MessageConstant.LOGIN_ERR_USER);
        }
        if (!admin.getPassword().trim().equals(adminQuery.getPassword())) {
            return new Result(Code.LOGIN_ERR, MessageConstant.LOGIN_ERR_PASS);
        }
        adminQuery.setPassword("***");

        // 计算过期时间：当前时间毫秒数 + 10秒的时间间隔
        Date now = new Date();
        Date expiryDate = new Date(now.getTime() + EXPIRY_INTERVAL); // 这里使用常量相加

        // 生成token
        String token = Jwts.builder()
                .setSubject(adminQuery.getUsername().trim())
                .setExpiration(expiryDate)
                .signWith(SignatureAlgorithm.HS512, SECRET_KEY)
                .compact();

        token = "Bearer " + token;
        log.info("当前token过期时间:{}", expiryDate);
        return new Result(Code.LOGIN_OK, token, MessageConstant.LOGIN_OK);
    }

    @GetMapping("/getAllEmployee")
    @CrossOrigin
    public Result getAllEmployee() {
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Employee::getUpdateTime);
        return new Result(Code.SELECT_OK, employeeMapper.selectList(queryWrapper));
    }

    @PostMapping("/EmployeeAdd")
    @CrossOrigin
    public Result EmployeeAdd(@RequestBody Employee employee) {
        //登录验证？
//        System.out.println("employee是"+employee);
        //验证数据库是否已有
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getEmployeeName, employee.getEmployeeName().trim());
        int count = employeeMapper.selectCount(queryWrapper);
        if (count > 0) {
            return new Result(Code.SAVE_ERR, "该员工已存在");
        }
        employee.setUpdateTime(now);
        int x = employeeMapper.insert(employee);
        if (x <= 0) {
            return new Result(Code.SAVE_ERR, "员工添加失败");
        }
        return new Result(Code.SAVE_OK, "员工添加成功");
    }

    @GetMapping("/EmployeeDelete")
    @CrossOrigin
    public Result EmployeeDelete(@Param("id") Long id) {
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getId, id);
        int count = employeeMapper.selectCount(queryWrapper);
        if (count == 0) {
            return new Result(Code.DELETE_ERR, "该员工信息不存在");
        }
        employeeMapper.delete(queryWrapper);
        return new Result(Code.DELETE_OK, "员工删除成功");
    }

//    @PostMapping("/login")
//    @CrossOrigin
//    public Result login(@RequestBody Admin admin) {
//        LambdaQueryWrapper<Admin> queryWrapper=new LambdaQueryWrapper<>();
//        queryWrapper.eq(Admin::getUsername,admin.getUsername().trim());
//        Admin adminQuery = adminService.getOne(queryWrapper);
//         if (adminQuery == null){
//             return new Result(Code.LOGIN_ERR, MessageConstant.LOGIN_ERR_USER);
//         }
//         //4、密码对比，不一致，失败
//         if (!admin.getPassword().trim().equals(adminQuery.getPassword())){
//             return new Result(Code.LOGIN_ERR,MessageConstant.LOGIN_ERR_PASS);
//         }
//        adminQuery.setPassword("***");
//        // 这里应该是你的用户验证逻辑，比如查询数据库
//        // 生成token
//        String token = Jwts.builder()
//                .setSubject(adminQuery.getUsername().trim()) // 将用户名存入token
//                .setExpiration(expiryDate) // 设置过期时间
//                .signWith(SignatureAlgorithm.HS512, SECRET_KEY) // 使用HS512算法进行签名
//                .compact();
//        log.info("过期时间是:"+expiryDate);
//        token = "Bearer " + token;
//        log.info("token:"+token);
//        System.out.println("新token:"+token);
//
//        return new Result(Code.LOGIN_OK,token, MessageConstant.LOGIN_OK);
//    }


//    @PostMapping("/login")
//    public Result adminLogin(HttpServletRequest request,
//                             HttpServletResponse response,
//                             @RequestBody Admin admin) throws ServletException, IOException {
//
//        String password=admin.getPassword();
//
//        LambdaQueryWrapper<Admin> queryWrapper=new LambdaQueryWrapper<>();
//        queryWrapper.eq(Admin::getUsername,admin.getUsername());
//
//        Admin adminQuery = adminService.getOne(queryWrapper);
//
//         if (adminQuery == null){
//             return new Result(Code.LOGIN_ERR, MessageConstant.LOGIN_ERR_USER);
//         }
//         //4、密码对比，不一致，失败
//         if (!password.equals(adminQuery.getPassword())){
//             return new Result(Code.LOGIN_ERR,MessageConstant.LOGIN_ERR_PASS);
//         }
//        adminQuery.setPassword("***");
//        // 用户名和密码验证成功，创建Cookie
//        Cookie loginCookie = new Cookie("username", adminQuery.getUsername());
//        loginCookie.setPath("/"); // 设置Cookie路径，通常设为根路径，使得整个应用都能访问
//        //如果不调用 setMaxAge() 方法/将其设置为 -1,
//        // Cookie 将在浏览器关闭时自动删除。
//        //setMaxAge(0): Cookie 将立即过期并被删除
////        loginCookie.setMaxAge(30 * 60); // 设置Cookie有效期为30分钟
//        //setMaxAge(2 * 24 * 60 * 60); // 2天
//        response.addCookie(loginCookie);
//        //在返回的Result中，确实只包含了 adminQuery。但 Cookie 本身会随 HTTP 响应自动发送。
//        // 因此，前端开发者接收到响应后，即使未在返回体中指定，
//        // 也可以通过浏览器的Cookie存储中访问到设置的Cookie。
//        return new Result(Code.LOGIN_OK,adminQuery, MessageConstant.LOGIN_OK);
//      }
}
